import { createSlice, createAsyncThunk, isRejectedWithValue } from "@reduxjs/toolkit";
import request from "../../utils/request";
import type { 
  UserState, 
  LoginRequest, 
  RegisterRequest,
  LoginResponse,
  RegisterResponse,
  ApiResponse 
} from "../../type/store";

// 定义异步action 
// 登录
export const userLogin = createAsyncThunk(
  "user/login", 
  async (users: LoginRequest): Promise<LoginResponse> => {
    try {
      const response = await request.post<ApiResponse<LoginResponse>>(
        `/api/health/user/v1/login`, 
        users, 
        {
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
          },
        }
      );
      return response.data.result || response.data.data || {};
    } catch (error: any) {
      return Promise.reject(
        error.message || "登录失败"
      );
    }
  }
);

// 获取验证码
export const userEmailCode = createAsyncThunk(
  "user/emailCode", 
  async (email: string): Promise<string> => {
    try {
      const response = await request.post<ApiResponse<{ code: string }>>(
        `/api/health/user/v1/sendOutEmailCode`, 
        email, 
        {
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
          },
        }
      );
      return response.data.result?.code || response.data.data?.code || "";
    } catch (error: any) {
      return Promise.reject(error.message || "获取验证码失败");
    }
  }
);

// 注册
export const userRegister = createAsyncThunk(
  "user/register", 
  async (users: RegisterRequest): Promise<RegisterResponse> => {
    try {
      const response = await request.post<ApiResponse<RegisterResponse>>(
        `/api/health/user/v1/register`, 
        users, 
        {
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
          },
        }
      );
      return response.data.result || response.data.data || {};
    } catch (error: any) {
      return Promise.reject(error.message || "注册失败");
    }
  }
);

const initialState: UserState = {
  count: 1,
  userData: null,
  status: "idle",
  error: "",
  loginres: {},
  registerres: {},
  emailCode: ""
};

const UserSlice = createSlice({
  name: "user",
  initialState,
  reducers: {
    clearError(state) {
      state.error = "";
    },
    resetStatus(state) {
      state.status = "idle";
    },
    logout(state) {
      state.userData = null;
      state.loginres = {};
      state.status = "idle";
    }
  },

  // 异步处理
  extraReducers: (builder) => {
    /* 登录状态 */
    builder //进行中
      .addCase(userLogin.pending, (state) => {
        state.status = "loading";
        state.error = "";
      }) // 成功状态
      .addCase(userLogin.fulfilled, (state, action) => {
        state.status = "succeeded";
        state.loginres = action.payload;
      }) // 失败状态
      .addCase(userLogin.rejected, (state, action) => {
        state.status = "failed";
        state.error = action.error.message || "登录失败";
      });

    /* 注册状态 */
    builder //进行中
      .addCase(userRegister.pending, (state) => {
        state.status = "loading";
        state.error = "";
      }) // 成功状态
      .addCase(userRegister.fulfilled, (state, action) => {
        state.status = "succeeded";
        state.registerres = action.payload;
      }) // 失败状态
      .addCase(userRegister.rejected, (state, action) => {
        state.status = "failed";
        state.error = action.error.message || "注册失败";
      });

    /* 验证码状态 */
    builder
      .addCase(userEmailCode.pending, (state) => {
        state.status = "loading";
        state.error = "";
      })
      .addCase(userEmailCode.fulfilled, (state, action) => {
        state.status = "succeeded";
        state.emailCode = action.payload;
      })
      .addCase(userEmailCode.rejected, (state, action) => {
        state.status = "failed";
        state.error = action.error.message || "获取验证码失败";
      });
  },
});

export const { clearError, resetStatus, logout } = UserSlice.actions;
export default UserSlice.reducer;
